基于JPA获取查询中的单条记录 - 木小鱼的笔记 - CSDN博客

创建时间:2019/1/9 14:45
来源:https://blog.csdn.net/blueheart20/article/details/78227473


版权声明:本文章是作者辛勤书写的成果,如需转载,请与作者联系,并保留作者信息以及原文链接,谢谢~~ https://blog.csdn.net/blueheart20/article/details/78227473

引言:JPA与SpringData中提供了诸多非常便利的方法,这里以如何以不书写SQL的方式来实现单条记录的查询。

repositories.limit-query-result

这个标题为Spring Data提供了内置功能,这些查询方法需要使用first/top等关键词,这两个关键词是彼此可以替代的。
可选的数字值用以表示最大可以返回的记录条数,一般都是放在first/top的右边。

Example 15. Limiting the result size of a query with Top and First

User findFirstByOrderByLastnameAsc();
User findTopByOrderByAgeDesc();
Page queryFirst10ByLastname(String lastname, Pageable pageable);
Slice findTop3ByLastname(String lastname, Pageable pageable);
List findFirst10ByLastname(String lastname, Sort sort);
List findTop10ByLastname(String lastname, Pageable pageable);

其中也是支持Distinct关键词的,限定词也可以支持Optional之类的关键词。
参考资料: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result

程序示例

实体类:

@Entity
@Table(name="t_user")
@Data
@EqualsAndHashCode(callSuper=true)
public class UserEntity extends BaseEntity {
    @Column(name="pin_key")
    private String userKey;
    @Column(name="device_type")
    private String deviceType;

        @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "created_time")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdTime;

    @Column(name = "updated_time")
    @Temporal(TemporalType.TIMESTAMP)

    @Version
    private long version;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

Repository的代码:

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
    public UserEntity findFirstByOrderByCreatedTimeDesc();
}
  • 1
  • 2
  • 3
  • 4

Service的示例代码:

@Slf4j
@Service
public class DemoService {
    @Autowired
    private UserRepository userRepo;

    .....
    public UserEntity getLatestUser() {
        return this.userRepo.findFirstByOrderByCreatedTimeDesc();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Controller的代码示例:

@Slf4j
@RestController
public class TestController {
    @Autowired
    private DemoService demoService;

    @GetMapping("/test/user")
    public String getUser() {
        UserEntity user = this.userRepo.findFirstByOrderByCreatedTimeDesc();

       log.info("userInfo:" + ReflectionToStringBuilder.toString(user));
       return user.toString();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

然后直接在浏览器打开连接就可以直接访问。
其余相关的配置项由于篇幅所限,就不在一一的黏贴拷贝了。

总结

Spring Data提供了大量非常好用的缺省实现,对于开发者而言直接使用即可,从而可以提升开发效率,充分体现瑞士军刀的锋利与效率。